package com.hhit.zhgd.service.impl

import cn.hutool.core.collection.CollUtil
import cn.hutool.core.date.DateUtil
import cn.hutool.core.util.ObjectUtil
import cn.hutool.core.util.StrUtil
import cn.hutool.poi.excel.ExcelUtil
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.metadata.IPage
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.hhit.zhgd.component.FileProperties
import com.hhit.zhgd.dao.ZhgdConstructionKeypointsMapper
import com.hhit.zhgd.domain.dto.ZhgdConstructionKeypointsDTO
import com.hhit.zhgd.domain.entity.ZhgdConstructionKeypoints
import com.hhit.zhgd.domain.response.BaseResp
import com.hhit.zhgd.service.ZhgdConstructionKeypointsService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.util.FileCopyUtils
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.FileOutputStream

@Service("zhgdConstructionKeypointsService")
class ZhgdConstructionKeypointsServiceImpl : ZhgdConstructionKeypointsService,
    ServiceImpl<ZhgdConstructionKeypointsMapper, ZhgdConstructionKeypoints>() {

    @Autowired
    private val fileProperties: FileProperties? = null

    override fun importConstructionKeypoints(multipartFile: MultipartFile?): BaseResp<Any?>? {
        this.remove(QueryWrapper())
        // 文件处理成io流
        val inputStream = multipartFile?.inputStream
        // io流给ExcelReader
        val excelReader = ExcelUtil.getReader(inputStream)
        val list = excelReader.read(1)
        val zhgdConstructionKeypointsList: MutableList<ZhgdConstructionKeypoints> = CollUtil.newArrayList()
        for (row in list) {
            if (StrUtil.isNotBlank(row[1].toString())) {
                val zhgdConstructionKeypoints =
                    ZhgdConstructionKeypoints(
                        sort = row[0].toString().toInt(),
                        name = row[1].toString(),
                        applicationRange = row[2].toString(),
                        qualityControlPoints = row[3].toString(),
                        qualityAcceptanceStandard = row[4].toString()
                    )
                zhgdConstructionKeypointsList.add(zhgdConstructionKeypoints)
            }
        }
        val saveBatchRes = this.saveBatch(zhgdConstructionKeypointsList)
        return if (saveBatchRes) {
            BaseResp.success()
        } else {
            BaseResp.fail("导入标准工艺数据失败!")
        }
    }

    override fun getConstructionKeypointsInfo(): List<ZhgdConstructionKeypoints?>? {
        return list(QueryWrapper<ZhgdConstructionKeypoints>().orderByAsc("sort"))
    }

    override fun importStandardTechnologyVideo(multipartFile: MultipartFile?, id: Int?): BaseResp<Any?>? {
        if (multipartFile == null || multipartFile?.isEmpty == true || ObjectUtil.isNull(id)) {
            return BaseResp.fail("上传失败!文件内容为空或者主键编号为空!")
        }
        // 获取文件名
        val fileName = multipartFile!!.originalFilename
        // 将文件写入nginx映射的存储路径
        val filePath: String = fileProperties?.parentPath + fileProperties?.path + fileName
        val file = File(filePath)
        multipartFile!!.transferTo(file)
        val fileAddress: String = filePath.replace(fileProperties?.parentPath ?: "", "")
        val zhgdConstructionKeypoints = getById(id)
        zhgdConstructionKeypoints.standardTechnologyVideo = fileAddress
        val updateRes = updateById(zhgdConstructionKeypoints)
        return if (updateRes) {
            BaseResp.success()
        } else {
            BaseResp.fail("上传标准工艺视频失败!")
        }
    }

    override fun addConstructionKeypoints(file: MultipartFile?): BaseResp<Any?>? {
        if (file == null || file?.isEmpty == true) {
            return BaseResp.fail("添加失败!文件为空!")
        }
        val filePath = java.lang.String.format(
            "%s%s%s",
            fileProperties?.parentPath,
            fileProperties?.path,
            file!!.originalFilename
        )
        FileCopyUtils.copy(file!!.inputStream, FileOutputStream(filePath))
        val zhgdConstructionKeypoints = ZhgdConstructionKeypoints()
        var name = file!!.originalFilename
        val dotIndex = name!!.lastIndexOf('.')
        if (dotIndex != -1) {
            name = name!!.substring(0, dotIndex)
        }
        zhgdConstructionKeypoints.name = name
        zhgdConstructionKeypoints.standardTechnologyVideo = filePath.replace(fileProperties?.parentPath ?: "", "")
        return if (save(zhgdConstructionKeypoints)) BaseResp.success() else BaseResp.fail("添加失败!")
    }

    override fun getConstructionKeypointsPageInfo(
        keyWord: String?,
        page: Int,
        size: Int
    ): IPage<ZhgdConstructionKeypointsDTO>? {
        val queryWrapper = QueryWrapper<ZhgdConstructionKeypoints>()
        if (StrUtil.isNotBlank(keyWord)) {
            queryWrapper.lambda().like(ZhgdConstructionKeypoints::name, keyWord)
        }
        val pageRequest = Page<ZhgdConstructionKeypoints>(page.toLong(), size.toLong())
        val zhgdConstructionKeypointsPage: IPage<ZhgdConstructionKeypoints> = this.page(pageRequest, queryWrapper)
        // Convert to DTO
        val dtoList = zhgdConstructionKeypointsPage.records
            .map { zhgdConstructionKeypoints ->
                val dto = ZhgdConstructionKeypointsDTO(
                    id = zhgdConstructionKeypoints.id,
                    fileUrl = zhgdConstructionKeypoints.standardTechnologyVideo,
                    name = zhgdConstructionKeypoints.name,
                    uploadTime = DateUtil.formatDateTime(zhgdConstructionKeypoints.createTime)
                )
                dto
            }.toCollection(ArrayList())
        val dtoPage: IPage<ZhgdConstructionKeypointsDTO> =
            Page(page.toLong(), size.toLong(), zhgdConstructionKeypointsPage.total)
        dtoPage.records = dtoList
        return dtoPage
    }

    override fun delConstructionKeypoints(id: Int?): BaseResp<Any?>? {
        if (ObjectUtil.isNull(id)) {
            return BaseResp.fail("无可删除的编号!")
        }
        return if (this.removeById(id)) BaseResp.success() else BaseResp.fail("删除失败!")
    }
}